package com.lerning.edu.manage.controller;

import com.alibaba.fastjson.JSONObject;
import com.lerning.edu.commons.util.DateUtil;
import com.lerning.edu.commons.util.StringUtil;
import com.lerning.edu.services.CampusDSRService;
import com.lerning.edu.services.WebTMKService;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author jiangwei
 * @since 18/8/2
 */
@Controller
@RequestMapping("WebTMK")
public class WebTMKController {

    @Autowired
    private WebTMKService webTMKService;
    @Autowired
    private CampusDSRService campusDSRService;

    @RequestMapping("/byTMK")
    @RequiresPermissions("view:WebTMK:byTMKbyTMK")
    public String byTMK(HttpServletRequest request,
                        @RequestParam(value = "SaleMode", required = false) String SaleMode,
                        @RequestParam(value = "BeginDate", required = false) String FBeginDate,
                        @RequestParam(value = "EndDate", required = false) String FEndDate) {
        String BeginDate;
        String EndDate;

        List byTMLList = new ArrayList();

        List querySaleModeByTMK = webTMKService.querySaleModeByTMK();

        Map map = new HashMap();
        map.put("SaleMode", SaleMode);

        if (StringUtil.isEmpty(FBeginDate) || StringUtil.isEmpty(FEndDate)) {
            List FinanceMonthOfDq = campusDSRService.queryNatureMonthOfDq(DateUtil.dayMap());//当前月

            Map dateMap = (HashMap) FinanceMonthOfDq.get(0);
            FBeginDate = dateMap.get("BeginDate").toString();
            FEndDate = dateMap.get("EndDate").toString();

            BeginDate = FBeginDate.substring(0, 10);
            EndDate = FEndDate.substring(0, 10);
        } else {

            BeginDate = FBeginDate.substring(0, 10);
            EndDate = FEndDate.substring(0, 10);

            map.put("FBeginDate", FBeginDate + " 00:00:00");
            map.put("FEndDate", FEndDate + " 23:59:59");
            map.put("BeginDate", BeginDate);
            map.put("EndDate", EndDate);

            byTMLList = webTMKService.queryWebTMKByTMK(map);
        }

        request.setAttribute("querySaleModeByTMK", querySaleModeByTMK);

        request.setAttribute("SaleMode", SaleMode);
        request.setAttribute("BeginDate", BeginDate);
        request.setAttribute("EndDate", EndDate);

        request.setAttribute("byTMLList", byTMLList);
        request.setAttribute("totalMap", sum(byTMLList));

        return "WebTMK/byTMK";
    }

    @RequestMapping("/detail")
    @ResponseBody
    public JSONObject detail(@RequestParam(value = "exportStartTime", required = false) String exportStartTime,
                             @RequestParam(value = "exportEndTime", required = false) String exportEndTime,
                             @RequestParam(value = "SaleMode", required = false) String exportSaleType,
                             @RequestParam(value = "info", required = false) String exportInfo,
                             @RequestParam(value = "cName", required = false) String cName,
                             @RequestParam(value = "cUserID", required = false)String cUserID) {

        Map map = new HashMap();
        map.put("BeginDate", exportStartTime + " 00:00:00");
        map.put("EndDate", exportEndTime + " 23:59:59");
        map.put("SaleMode", exportSaleType);
        map.put("cField5", cName);
        map.put("cUserID", cUserID);

        map.put("BeginDateShow", exportStartTime);
        map.put("EndDateShow", exportEndTime);

        List detail = new ArrayList();

        if (exportInfo.equals("Leads")) {
            detail = webTMKService.queryDetail(map);
        } else if (exportInfo.equals("APP")) {
            detail = webTMKService.queryDetailByApp(map);
        } else if (exportInfo.equals("Show")) {

            detail = webTMKService.queryDetailByShow(map);
        } else if (exportInfo.equals("En")) {
            detail = webTMKService.queryDetailByEn(map);
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data", detail);
        return jsonObject;
    }

    /***
     * 导出
     *
     * @param response
     * @param exportStartTime
     * @param exportEndTime
     * @param exportSaleType
     * @param exportInfo
     * @throws Exception
     */
    @RequestMapping("/exportInfo")
    public void exportInfo(HttpServletResponse response,
                           @RequestParam(value = "exportStartTime", required = false) String exportStartTime,
                           @RequestParam(value = "exportEndTime", required = false) String exportEndTime,
                           @RequestParam(value = "exportSaleType", required = false) String exportSaleType,
                           @RequestParam(value = "exportInfo", required = false) String exportInfo) throws Exception {

        Map map = new HashMap();
        map.put("BeginDate", exportStartTime + " 00:00:00");
        map.put("EndDate", exportEndTime + " 23:59:59");
        map.put("SaleMode", exportSaleType);

        map.put("BeginDateShow", exportStartTime);
        map.put("EndDateShow", exportEndTime);

        HSSFWorkbook workbook = new HSSFWorkbook();
        // 生成一个表格
        HSSFSheet sheet = workbook.createSheet(exportInfo);
        // 设置表格默认列宽度为15个字节
        sheet.setDefaultColumnWidth((short) 15);
        // 产生表格标题行
        HSSFRow row = sheet.createRow(0);
        HSSFCell cell = row.createCell(0);
        HSSFCell cell1 = row.createCell(1);
        HSSFCell cell2 = row.createCell(2);
        HSSFCell cell3 = row.createCell(3);


        cell.setCellValue("姓名");
        cell1.setCellValue("手机号");
        cell2.setCellValue("校区");
        cell3.setCellValue("主责任人");

        List detail = new ArrayList();

        if (exportInfo.equals("Leads")) {
            detail = webTMKService.queryDetail(map);
        } else if (exportInfo.equals("APP")) {
            detail = webTMKService.queryDetailByApp(map);
        } else if (exportInfo.equals("Show")) {
            detail = webTMKService.queryDetailByShow(map);
        } else if (exportInfo.equals("En")) {
            detail = webTMKService.queryDetailByEn(map);
        }

        if (detail.size() > 0) {
            for (int i = 0; i < detail.size(); i++) {
                HSSFRow rowValue = sheet.createRow(1 + i);
                HSSFCell cellDate = rowValue.createCell(0);
                HSSFCell cellDate1 = rowValue.createCell(1);
                HSSFCell cellDate2 = rowValue.createCell(2);
                HSSFCell cellDate3 = rowValue.createCell(3);

                Map appMap = (HashMap) detail.get(i);

                cellDate.setCellValue(appMap.get("cName").toString());
                cellDate1.setCellValue(appMap.get("cSMSTel").toString());
                cellDate2.setCellValue(appMap.get("campusID").toString());
                cellDate3.setCellValue(appMap.get("cField5").toString());
            }
        }

        ServletOutputStream outputStream = null;// 创建一个输出流对象
        try {
            response.setContentType("application/binary;charset=utf-8");
            String headerStr = new String((exportInfo).getBytes("utf-8"), "ISO8859-1");// headerString为中文时转码
            response.setHeader("Content-disposition", "attachment; filename=" + headerStr + ".xls");// filename是下载的xls的名
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/byCampus")
    @RequiresPermissions("view:WebTMK:byTMKbyCampus")
    public String byCampus(HttpServletRequest request,
                           @RequestParam(value = "SaleMode", required = false) String SaleMode,
                           @RequestParam(value = "BeginDate", required = false) String FBeginDate,
                           @RequestParam(value = "EndDate", required = false) String FEndDate) {
        String BeginDate;
        String EndDate;

        List byCampusList = new ArrayList();

        List querySaleModeByTMK = webTMKService.querySaleModeByTMK();

        Map map = new HashMap();
        map.put("SaleMode", SaleMode);

        if (StringUtil.isEmpty(FBeginDate) || StringUtil.isEmpty(FEndDate)) {
            List FinanceMonthOfDq = campusDSRService.queryNatureMonthOfDq(DateUtil.dayMap());//当前月

            Map dateMap = (HashMap) FinanceMonthOfDq.get(0);
            FBeginDate = dateMap.get("BeginDate").toString();
            FEndDate = dateMap.get("EndDate").toString();

            BeginDate = FBeginDate.substring(0, 10);
            EndDate = FEndDate.substring(0, 10);
        } else {

            BeginDate = FBeginDate.substring(0, 10);
            EndDate = FEndDate.substring(0, 10);

            map.put("FBeginDate", FBeginDate + " 00:00:00");
            map.put("FEndDate", FEndDate + " 23:59:59");
            map.put("BeginDate", BeginDate);
            map.put("EndDate", EndDate);

            byCampusList = webTMKService.queryWebTMKByCampus(map);
        }

        request.setAttribute("querySaleModeByTMK", querySaleModeByTMK);

        request.setAttribute("SaleMode", SaleMode);
        request.setAttribute("BeginDate", BeginDate);
        request.setAttribute("EndDate", EndDate);

        request.setAttribute("byCampusList", byCampusList);

        request.setAttribute("totalMap", sumByCampus(byCampusList));

        return "WebTMK/byCampus";
    }

    @RequestMapping("/exportByCampus")
    public void exportByCampus(HttpServletResponse response,
                           @RequestParam(value = "exportStartTime", required = false) String exportStartTime,
                           @RequestParam(value = "exportEndTime", required = false) String exportEndTime,
                           @RequestParam(value = "exportSaleType", required = false) String exportSaleType) throws Exception {

        Map map = new HashMap();
        map.put("BeginDate", exportStartTime);
        map.put("EndDate", exportEndTime);
        map.put("FBeginDate", exportStartTime + " 00:00:00");
        map.put("FEndDate", exportEndTime + " 23:59:59");
        map.put("SaleMode", exportSaleType);

        HSSFWorkbook workbook = new HSSFWorkbook();
        // 生成一个表格
        HSSFSheet sheet = workbook.createSheet("校区TMK");
        // 设置表格默认列宽度为15个字节
        sheet.setDefaultColumnWidth((short) 15);
        // 产生表格标题行
        HSSFRow row = sheet.createRow(0);
        HSSFCell cell = row.createCell(0);
        HSSFCell cell1 = row.createCell(1);
        HSSFCell cell2 = row.createCell(2);
        HSSFCell cell3 = row.createCell(3);
        HSSFCell cell4 = row.createCell(4);
        HSSFCell cell5 = row.createCell(5);


        cell.setCellValue("区域");
        cell1.setCellValue("校区");
        cell2.setCellValue("Leads");
        cell3.setCellValue("APP");
        cell4.setCellValue("Show");
        cell5.setCellValue("Erollment");

        List detail = webTMKService.queryWebTMKByCampus(map);


        if (detail.size() > 0) {
            for (int i = 0; i < detail.size(); i++) {
                HSSFRow rowValue = sheet.createRow(1 + i);
                HSSFCell cellDate = rowValue.createCell(0);
                HSSFCell cellDate1 = rowValue.createCell(1);
                HSSFCell cellDate2 = rowValue.createCell(2);
                HSSFCell cellDate3 = rowValue.createCell(3);
                HSSFCell cellDate4 = rowValue.createCell(4);
                HSSFCell cellDate5 = rowValue.createCell(5);

                Map appMap = (HashMap) detail.get(i);

                cellDate.setCellValue(appMap.get("cTel").toString());
                cellDate1.setCellValue(appMap.get("cName").toString());
                cellDate2.setCellValue(appMap.get("leadsCount").toString());
                cellDate3.setCellValue(appMap.get("appCount").toString());
                cellDate4.setCellValue(appMap.get("showCount").toString());
                cellDate5.setCellValue(appMap.get("enCount").toString());

            }
        }

        ServletOutputStream outputStream = null;// 创建一个输出流对象
        try {
            response.setContentType("application/binary;charset=utf-8");
            String headerStr = new String((exportStartTime+"到"+exportEndTime).getBytes("utf-8"), "ISO8859-1");// headerString为中文时转码
            response.setHeader("Content-disposition", "attachment; filename=" + headerStr + ".xls");// filename是下载的xls的名
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public Map sum(List list) {
        Map map = new HashMap();

        int leads = 0;
        int app = 0;
        int show = 0;
        int en = 0;

        if (list.size() > 0) {
            for (Object obj : list) {
                Map objMap = (HashMap) obj;
                leads = leads + (int) objMap.get("leadsCount");
                app = app + (int) objMap.get("appCount");
                show = show + (int) objMap.get("showCount");
                en = en + (int) objMap.get("enCount");
            }
            map.put("leads", leads);
            map.put("app", app);
            map.put("show", show);
            map.put("en", en);

            if (app != 0) {
                double ratio = new BigDecimal(show).divide(new BigDecimal(app), 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).doubleValue();
                map.put("totalRatio", ratio);
            } else {
                map.put("totalRatio", 0);
            }
        } else {
            map.put("leads", 0);
            map.put("app", 0);
            map.put("show", 0);
            map.put("en", 0);
            map.put("totalRatio", 0);
        }
        return map;
    }

    public Map sumByCampus(List list){
        Map map = new HashMap();

        int leads = 0;
        int app = 0;
        int show = 0;
        int en = 0;

        if (list.size() > 0) {
            for (Object obj : list) {
                Map objMap = (HashMap) obj;
                app = app + (int) objMap.get("appCount");
                show = show + (int) objMap.get("showCount");
                en = en + (int) objMap.get("enCount");
            }
            map.put("leads", leads);
            map.put("app", app);
            map.put("show", show);
            map.put("en", en);

            if (app != 0) {
                double ratio = new BigDecimal(show).divide(new BigDecimal(app), 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).doubleValue();
                map.put("totalASRatio", ratio);
            } else {
                map.put("totalASRatio", 0);
            }

            if (app != 0) {
                double ratio = new BigDecimal(show).divide(new BigDecimal(app), 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).doubleValue();
                map.put("totalESRatio", ratio);
            } else {
                map.put("totalESRatio", 0);
            }
        } else {
            map.put("leads", 0);
            map.put("app", 0);
            map.put("show", 0);
            map.put("en", 0);
            map.put("totalASRatio", 0);
            map.put("totalESRatio", 0);
        }
        return map;
    }
}
